<template>
  <div class="baseInfo">
    <div class="baseInfo-header" v-if="!readonly">
      <el-button type="primary" size="small" @click="addEmptyRow">新增</el-button>
    </div>
    <vxe-table border stripe ref="tableRef" size="small" header-align="center" :row-config="rowConfig"
      :column-config="columnConfig" :data="tableData">
      <vxe-column type="seq" width="50" title="序号" align="center" fixed="left" />
      <vxe-column v-if="!readonly" width="80" title="操作" align="center" fixed="left">
        <template #default="{ rowIndex }">
          <el-button size="mini" type="text" @click="handleDelete(rowIndex)">删除</el-button>
        </template>
      </vxe-column>
      <vxe-column field="productCode" title="商品编码" align="center" width="120">
        <template #default="{ row }">
          <span v-if="!readonly" class="product-code-selectable" style="color: #409EFF; cursor: pointer;"
            @click="onProductCodeClick(row)" >
            {{ row.productCode ? row.productCode : '请选择' }}
          </span>
          <span v-else>
            {{ row.productCode }}
          </span>
        </template>
      </vxe-column>
      <vxe-column field="productName" title="商品名称" align="center" width="140" />
      <vxe-column field="imageUrl" title="图片" align="center" width="70">
        <template #default="{ row }">
          <img v-if="row.imageUrl" :src="row.imageUrl" style="width:40px;height:40px;object-fit:contain;" />
        </template>
      </vxe-column>
      <vxe-column field="specification" title="规格信息" align="center" width="120" />
      <vxe-column field="preSale" title="是否预售" align="center" width="90">
        <template #default="{ row }">
          <el-select v-if="!readonly" v-model="row.preSale" size="mini" style="width:80px">
            <el-option label="是" value="是" />
            <el-option label="否" value="否" />
          </el-select>
          <span v-else>{{ row.preSale || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="predictDeliveryTime" title="预计发货时间" align="center" width="120">
        <template #default="{ row }">
          <el-date-picker v-if="!readonly" v-model="row.predictDeliveryTime" type="date" size="mini" value-format="yyyy-MM-dd"
            placeholder="选择日期" style="width:110px" />
          <span v-else>{{ row.predictDeliveryTime || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="warehouseName" title="仓库名称" align="center" width="120">
        <template #default="{ row }">
          <el-select v-if="!readonly" v-model="row.warehouseName" size="mini" style="width:100px">
            <el-option v-for="item in warehouseList" :key="item.warehouseId" :label="item.warehouseName"
              :value="item.warehouseName" />
          </el-select>
          <span v-else>{{ row.warehouseName || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="allowNegativeStock" title="允许负库存" align="center" width="100" />
      <vxe-column field="gift" title="是否赠品" align="center" width="90">
        <template #default="{ row }">
          <el-select v-if="!readonly" v-model="row.gift" size="mini" style="width:80px">
            <el-option label="否" value="否" />
            <el-option label="是" value="是" />
          </el-select>
          <span v-else>{{ row.gift || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="platformProductCode" title="平台商品编码？" align="center" width="120">
        <template #default="{ row }">
          <span v-if="!readonly" class="product-code-selectable" style="color: #409EFF; cursor: pointer;"
            @click="onPlatformProductCodeClick(row)">
            {{ row.platformProductCode ? row.platformProductCode : '请选择' }}
          </span>
          <span v-else>
            {{ row.platformProductCode }}
          </span>
        </template>
      </vxe-column>

      <vxe-column field="platformProductName" title="平台商品名称" align="center" width="140" />
      <vxe-column field="platformProductInfo" title="平台商品规格?" align="center" width="120" />
      <vxe-column field="quantity" title="数量" align="center" width="150">
        <template #default="{ row }">
          <el-input-number v-if="!readonly" v-model="row.quantity" size="mini" :min="0" />
          <span v-else>{{ row.quantity || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="salableQuantity" title="可销售数" align="center" width="100" />
      <vxe-column field="prepareQuantity" title="可配数" align="center" width="100" />
      <vxe-column field="discount" title="折扣" align="center" width="150">
        <template #default="{ row }">
          <el-input-number v-if="!readonly" v-model="row.discount" size="mini" :min="0" :max="1" :step="0.01" />
          <span v-else>{{ row.discount || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="stdPrice" title="标准单价" align="center" width="150">
        <template #default="{ row }">
          <el-input-number v-if="!readonly" v-model="row.stdPrice" size="mini" :min="0" :step="0.01" />
          <span v-else>{{ row.stdPrice || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="stdAmount" title="标准金额" align="center" width="150">
        <template #default="{ row }">
          <span>{{ calcStdAmount(row) }}</span>
        </template>
      </vxe-column>
      <vxe-column field="actualPrice" title="实际单价" align="center" width="150">
        <template #default="{ row }">
          <el-input-number v-if="!readonly" v-model="row.actualPrice" size="mini" :min="0" :step="0.01" />
          <span v-else>{{ row.actualPrice || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="actualAmount" title="实际金额" align="center" width="130">
        <template #default="{ row }">
          <span>{{ calcActualAmount(row) }}</span>
        </template>
      </vxe-column>
      <vxe-column field="onSaleAmount" title="让利金额" align="center" width="130">
        <template #default="{ row }">
          <span>{{ calcOnSaleAmount(row) }}</span>
        </template>
      </vxe-column>
      <vxe-column field="expressFee" title="物流费用" align="center" width="150">
        <template #default="{ row }">
          <el-input-number v-if="!readonly" v-model="row.expressFee" size="mini" :min="0" :step="0.01" />
          <span v-else>{{ row.expressFee || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="otherFee" title="其他费用" align="center" width="150">
        <template #default="{ row }">
          <el-input-number v-if="!readonly" v-model="row.otherFee" size="mini" :min="0" :step="0.01" />
          <span v-else>{{ row.otherFee || '-' }}</span>
        </template>
      </vxe-column>
      <vxe-column field="remark" title="备注" align="center" width="120">
        <template #default="{ row }">
          <el-input v-if="!readonly" v-model="row.remark" size="mini" placeholder="请输入备注" />
          <span v-else>{{ row.remark || '-' }}</span>
        </template>
      </vxe-column>
    </vxe-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <el-dialog title="选择商品" :visible.sync="selectGoodsDialogVisible" width="900px" append-to-body destroy-on-close>
      <selectGoods @selected="handleGoodsSelected" />
    </el-dialog>
    <el-dialog title="选择平台商品" :visible.sync="platformSelectDialogVisible" width="900px" append-to-body destroy-on-close>
      <selectPlatformGoods @selected="handlePlatformProductSelected" :platform="true" />
    </el-dialog>
  </div>
</template>

<script>
import {
  listGoodsByOrderId
} from "@/api/mes/sales/saleOrder";
import ItemSelect from "@/components/itemSelect/single.vue";
import selectGoods from "../innerComponents/selectGoods.vue";
import selectPlatformGoods from "../innerComponents/selectPlatformGoods.vue";
export default {
  name: 'address',
  props: {
    readonly: {
      type: Boolean,
      default: false
    },
    cellId: undefined,
    warehouseList: [], // 仓库下拉：
  },
  computed: {
  },
  components: {
    ItemSelect,
    selectGoods,
    selectPlatformGoods,
  },
  data() {
    return {
      tableData: [],
      selectGoodsDialogVisible: false,
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      rowConfig: {
        keyField: '',
        isHover: true,
        isCurrent: true,
      },
      columnConfig: {
        resizable: true,
        align: 'center',
        headerAlign: 'center',
      },
      selectingRow: null, platformSelectingRow: null,
      platformSelectDialogVisible: false,

    }
  },
  watch: {
    cellId: {
      immediate: true,
      handler(val) {
        // cellId为真实id时可请求数据，否则初始化空表
        if (val && val !== 'add') {
          this.getList();
        } else {
          this.tableData = [];
        }
      },
    }
  },
  methods: {
    getList() {
      listGoodsByOrderId(this.cellId).then(res => {
        if (res.code === 200) {
          this.tableData = res.data?.proOrderProductList || [];
        }
      })
    },
    // 计算标准金额
    calcStdAmount(row) {
      const qty = Number(row.quantity) || 0;
      const price = Number(row.stdPrice) || 0;
      return (qty * price).toFixed(2);
    },
    // 计算实际金额
    calcActualAmount(row) {
      const qty = Number(row.quantity) || 0;
      const price = Number(row.actualPrice) || 0;
      return (qty * price).toFixed(2);
    },
    // 计算让利金额
    calcOnSaleAmount(row) {
      const stdAmount = parseFloat(this.calcStdAmount(row)) || 0;
      const actualAmount = parseFloat(this.calcActualAmount(row)) || 0;
      return (stdAmount - actualAmount).toFixed(2);
    },
    onPlatformProductCodeClick(row) {
      this.platformSelectingRow = row;
      this.platformSelectDialogVisible = true;
    },
    handlePlatformProductSelected(selectedGoods) {
      // 只更新当前行，字段与平台商品弹窗一致
      if (this.platformSelectingRow && selectedGoods && selectedGoods.length > 0) {
        const item = selectedGoods[0];
        Object.assign(this.platformSelectingRow, {
          platformProductCode: item.platformProductCode || '',
          platformProductName: item.platformProductName || '',
          platformProductInfo: item.platformProductInfo || '',
        });
        this.platformSelectingRow = null;
        this.platformSelectDialogVisible = false;
      }
    },
    onProductCodeClick(row) {
      this.selectingRow = row;
      this.selectGoodsDialogVisible = true;
    },
    handleGoodsSelected(selectedGoods) {
      // 单选：直接修改当前行
      if (this.selectingRow && selectedGoods && selectedGoods.length > 0) {
        const item = selectedGoods[0];
        Object.assign(this.selectingRow, {
          productCode: item.productCode,
          productName: item.productName,
          imageUrl: item.imageUrl,
          specification: item.specification,
          productId: item.productId,
          // 其它字段可按需补充
        });
        this.selectingRow = null;
        this.selectGoodsDialogVisible = false;
        return;
      }
      // 兼容批量选择（如后续扩展）
      // const codes = this.tableData.map(item => item.productCode);
      // const newRows = selectedGoods.filter(item => !codes.includes(item.productCode)).map(item => ({
      //   productCode: item.productCode,
      //   productName: item.productName,
      //   imageUrl: item.imageUrl,
      //   specification: item.specification,
      //   preSale: '否',
      //   predictDeliveryTime: '',
      //   warehouseName: '',
      //   allowNegativeStock: '允许',
      // }));
      // this.tableData = this.tableData.concat(newRows);
      // this.selectGoodsDialogVisible = false;
    },
    addEmptyRow() {
      this.tableData.push({
        productCode: '',
        productName: '',
        imageUrl: '',
        specification: '',
        preSale: '否',
        predictDeliveryTime: '',
        warehouseName: '',
        gift: '',
        platformProductCode: '',
        platformProductName: '',
        platformProductInfo: '',
        quantity: 0,
        salableQuantity: '',
        prepareQuantity: '',
        discount: 0.1,
        stdPrice: 0,
        stdAmount: '',
        actualPrice: 0,
        actualAmount: '',
        onSaleAmount: '',
        expressFee: 0,
        otherFee: 0,
        remark: ''
      });
    },
    handleDelete(rowIndex) {
      this.tableData.splice(rowIndex, 1);
    },

  },
  // ...methods结束
}
</script>

<style lang="scss" scoped>
.product-code-selectable {
  user-select: none;
  transition: color 0.2s;
}

.product-code-selectable:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.baseInfo {
  &-header {
    margin-bottom: 10px;
  }
}

// 只读模式下的文本样式优化
::v-deep .vxe-body--column {
  .vxe-cell {
    span {
      color: #606266;
      font-size: 13px;
      line-height: 1.4;
      
      &:not(:empty) {
        padding: 2px 4px;
      }
    }
  }
}
</style>